<?php

namespace App\Http\Controllers\Auth\Owner;

use DB;
use Log;
use Reheat\Sms\SmsDebug;
use Illuminate\Support\Str;
use Common\Models\User\User;
use Illuminate\Http\Request;
use Common\Models\User\UserOwner;
use Illuminate\Support\Facades\Hash;
use Common\Services\User\UserService;
use Reheat\Laravel\Facades\ApiResponse;
use Common\Services\User\UserDeviceService;
use Common\Resources\Auth\AuthorizationResource;

/**
 * 认证服务
 *
 * @license [http://www.85do.com] [杭州永奥网络科技有限公司]
 * @copyright Copyright (c) 2018-2026 Hangzhou Yongao Technology Co., Ltd. All rights reserved.
 */
class AuthController extends Controller
{
    /**
     * 注册.
     */
    public function register(Request $request)
    {
        //数据验证
        $this->validate($request, [
            'mobile'            => 'required|regex:/^1[2345789][0-9]{9}$/',
            'password'          => 'required|min:5|max:32',
            'verification_code' => 'required|integer|max:999999',
            'contact'           => 'required|max:32',
            'institution'       => 'required|max:128',
        ], [
            'mobile.required'            => trans('common.validate_mobile_required'),
            'mobile.regex'               => trans('common.validate_mobile_regex'),
            'password.required'          => trans('common.validate_password_required'),
            'password.min'               => trans('common.validate_password_min'),
            'password.max'               => trans('common.validate_password_max'),
            'verification_code.required' => trans('common.validate_verification_code_required'),
            'verification_code.integer'  => trans('common.validate_verification_code_integer'),
            'verification_code.max'      => trans('common.validate_verification_code_max'),
            'contact.required'           => trans('auth.validate_contact_required'),
            'contact.max'                => trans('auth.validate_contact_max'),
            'institution.required'       => trans('auth.validate_institution_required'),
            'institution.max'            => trans('auth.validate_institution_max'),
        ]);

        // 数据获取
        $mobile            = $request->post('mobile');
        $password          = $request->post('password');
        $verification_code = $request->post('verification_code');
        $contact           = $request->post('contact');
        $institution       = $request->post('institution');

        // 检测验证码(debug模式)
        if (config('app.debug')) {
            $sms       = new SmsDebug();
            $stdReturn = $sms->checkCode($mobile, $verification_code);
            if (! $sms->isSuccess()) {
                return ApiResponse::std($stdReturn);
            }
        } else {
            $sms       = new JiGuangSMS();
            $stdReturn = $sms->checkCode($mobile, $verification_code);
            if (! $sms->isSuccess()) {
                return ApiResponse::std($stdReturn);
            }
        }

        // 唯一性检测
        $user = User::where('mobile', $mobile)->first();
        if ($user) {
            return ApiResponse::error(trans('common.tips_mobile_used'));
        }

        // 注册事务
        DB::beginTransaction();
        try {
            //主用户
            $user           = new User();
            $user->mobile   = $mobile;
            $user->username = $mobile;
            $user->nickname = UserService::defaultNickname();
            $user->salt     = Str::random(6);
            $user->password = Hash::make(md5($password.$user->salt));
            $user->save();

            $userOwner              = new UserOwner();
            $userOwner->user_id     = $user->id;
            $userOwner->contact     = $contact;
            $userOwner->institution = $institution;
            $userOwner->save();

            $user->owner = $userOwner;

            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            Log::error('注册事务操作失败： '.$e->getMessage());

            return ApiResponse::error(trans('auth.tips_registration_failure'));
        }

        return new AuthorizationResource($user);
    }

    /**
     * 登录.
     */
    public function login(Request $request)
    {
        $this->validate($request, [
            'phone'    => 'required|min:5|max:11|regex:/^1[34578][0-9]{9}$/',
            'password' => 'required|min:5|max:32',
        ], [
            'phone.required'    => trans('common.validate_phone_required'),
            'phone.regex'       => trans('common.validate_phone_regex'),
            'password.required' => trans('common.validate_password_required'),
            'password.min'      => trans('common.validate_password_min'),
            'password.max'      => trans('common.validate_password_max'),
        ]);

        $phone    = $request->post('phone');
        $password = $request->post('password');

        /*
        |--------------------------------------------------------------------------
        | 用户名验证
        |--------------------------------------------------------------------------
        */
        $user = User::where('phone', $phone)->first();
        if (! $user) {
            return ApiResponse::error('用户名或者密码错误');
        }
        /*
        |--------------------------------------------------------------------------
        | 验证禁用状态
        |--------------------------------------------------------------------------
        */
        if (0 == $user->active) {
            return ApiResponse::error('账号已禁用');
        }
        /*
        |--------------------------------------------------------------------------
        | 密码验证
        |--------------------------------------------------------------------------
        */
        $password = md5($password.$user->salt); //密码混淆
        if (! Hash::check($password, $user->password)) {
            return ApiResponse::error('用户名或者密码错误');
        }
        //检测密码是否需要更新
        if (Hash::needsRehash($user->password)) {
            $user->password = Hash::make($password); //更新密码
            Log::debug("用户{$user->username}密码被更新");
        }

        //保存用户设备参数
        UserDeviceService::save($user, $request);

        return ApiResponse::data(new AuthorizationResource($user));
    }

    /**
     * 手机登录.
     */
    public function phone(Request $request)
    {
        //数据验证
        $this->validate($request, [
            'phone'             => 'required|regex:/^1[2345789][0-9]{9}$/',
            'verification_code' => 'required|integer|max:999999',
        ], [
            'phone.required'    => trans('common.validate_phone_required'),
            'phone.regex'       => trans('common.validate_phone_regex'),
            'password.required' => trans('common.validate_password_required'),
            'password.min'      => trans('common.validate_password_min'),
            'password.max'      => trans('common.validate_password_max'),
        ]);

        // 数据获取
        $phone             = $request->post('phone');
        $verification_code = $request->post('verification_code');

        // 检测验证码(debug模式)
        if (config('app.debug')) {
            $sms       = new SmsDebug();
            $stdReturn = $sms->checkCode($phone, $verification_code);
            if (! $sms->isSuccess()) {
                return ApiResponse::std($stdReturn);
            }
        } else {
            $sms       = new JiGuangSMS();
            $stdReturn = $sms->checkCode($phone, $verification_code);
            if (! $sms->isSuccess()) {
                return ApiResponse::std($stdReturn);
            }
        }

        // 账号名验证
        $user = User::where('phone', $phone)->first();
        if (is_null($user)) {
            return ApiResponse::error('账号不存在');
        }

        // 验证禁用状态
        if (0 == $user->active) {
            return ApiResponse::error('账号已禁用');
        }

        return ApiResponse::data(new AuthorizationResource($user));
    }

    /**
     * 重置密码
     */
    public function resetPassword(Request $request)
    {
        //数据验证
        $this->validate($request, [
            'phone'             => 'required|regex:/^1[2345789][0-9]{9}$/',
            'new_password'      => 'required|min:5|max:32',
            'verification_code' => 'required|integer|max:999999',
        ], [
            'phone.required'             => trans('common.validate_phone_required'),
            'phone.regex'                => trans('common.validate_phone_regex'),
            'password.required'          => trans('common.validate_password_required'),
            'password.min'               => trans('common.validate_password_min'),
            'password.max'               => trans('common.validate_password_max'),
            'verification_code.required' => trans('common.validate_verification_code_required'),
            'verification_code.integer'  => trans('common.validate_verification_code_integer'),
            'verification_code.max'      => trans('common.validate_verification_code_max'),
        ]);

        // 数据获取
        $phone             = $request->post('phone');
        $new_password      = $request->post('new_password');
        $verification_code = $request->post('verification_code');

        // 检测验证码(debug模式)
        if (config('app.debug')) {
            $sms       = new SmsDebug();
            $stdReturn = $sms->checkCode($phone, $verification_code);
            if (! $sms->isSuccess()) {
                return ApiResponse::std($stdReturn);
            }
        } else {
            $sms       = new JiGuangSMS();
            $stdReturn = $sms->checkCode($phone, $verification_code);
            if (! $sms->isSuccess()) {
                return ApiResponse::std($stdReturn);
            }
        }

        // 验证用户
        $user = User::where('phone', $phone)->first();
        if (! $user) {
            return ApiResponse::error('密码重置失败,账号未找到');
        }

        // 更新密码
        $user->password = Hash::make(md5($new_password.$user->salt));
        $user->update();

        return ApiResponse::success('密码重置成功');
    }
}
